//
//  AddNewProfile_VC.m
//  KaChing_App
//
//  Created by Jordan Robert Yust on 2/23/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "AddNewProfile_VC.h"
#import "Constants.h"

@implementation AddNewProfile_VC

@synthesize profileName;
@synthesize userID;
@synthesize remoteKey;
@synthesize returnButton;
@synthesize userDictionary;
@synthesize settings_TableView;

- (void)dealloc
{
	/* To adhere to memory management, each object that's an IBOutlet (created when
	 the nib file is loaded) needs to then be released in this method. */
	[userID release];
	[remoteKey release];
	[profileName release];
	[returnButton release];
	[userDictionary release];
	[settings_TableView release];
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // Dismiss the keyboard when the view outside the text field(s) is touched.
    [userID resignFirstResponder];
	[remoteKey resignFirstResponder];
	[profileName resignFirstResponder];
	
    [super touchesBegan:touches withEvent:event];
}

/*
 ------------------------------------------------------------------------
ViewController methods
 ------------------------------------------------------------------------
 */

#pragma mark -
#pragma mark ViewController methods

/*
// Override initWithNibName:bundle: to load the view using a nib file then perform additional customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically.
- (void)loadView {
}
*/


// Implement viewDidLoad to do additional setup after loading the view.
- (void)viewDidLoad
{
	self.returnButton.hidden = TRUE;
	
	/* Creates the button for selecting the profile (and specifies the method to be called when the button is clicked) */
	UIBarButtonItem *saveButton = [[UIBarButtonItem alloc] initWithTitle:@"Save!" 
																   style:UIBarButtonItemStylePlain 
																	target:self
																	action:@selector(saveButtonClicked)];
	
	self.navigationItem.rightBarButtonItem = saveButton;
	[saveButton release];
	
    [super viewDidLoad];
}


/*
 ------------------------------------------------------------------------
IBAction methods
 ------------------------------------------------------------------------
 */

#pragma mark -
#pragma mark IBAction methods

/* This method is called when the user wants to save the profile. */
- (void) saveButtonClicked
{
	/* If not all textfields have text in them... */
	if ([self.userID.text length] == 0 || [self.remoteKey.text length] == 0 || [self.profileName.text length] == 0)
	{
		/* Displays an AlertView showing insufficient criteria */
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Insufficient Criteria" message:@"Please fill in all required fields."
													   delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
		[alert show];
		[alert release];
	}
	/* Each textField contains an entry.. */
	else
	{
		/* Adds an entry into the dictionary for each of the profile's characteristics */
		[[userDictionary objectForKey:@"ProfileNames"] addObject:self.profileName.text];
		[[userDictionary objectForKey:@"UserIDs"] addObject:self.userID.text];
		[[userDictionary objectForKey:@"RemoteKeys"] addObject:self.remoteKey.text];
	
		/* Save the contents of the created profile as defaults (to ensure the new profile is saved between application launchings) */
		NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];		
		[preferences setObject:userDictionary forKey:@"UserDictionary"];
		
		/* Updates the contents of the settings' table view so that it displays the newly created profile */
		[settings_TableView reloadData];
		
		/* Pop this view of the navigation controller's stack.  This transitions back to the previous view. */
		[self.navigationController popViewControllerAnimated:YES];
	}
}

- (IBAction) resignUserID_Responder
{
	[self.userID resignFirstResponder];
}

/*
 ------------------------------------------------------------------------
 UITextFieldDelegate protocol methods
 ------------------------------------------------------------------------
 */

#pragma mark -
#pragma mark UITextFieldDelegate Protocol methods

/*
 This method is called whenever the user taps the return method
 NOTE: This is part of the UITextFieldDelegate Protocol.
 */
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	/* Resign First Responder (hide the keyboard) */
	if (textField == self.profileName || textField == self.remoteKey || textField == self.userID)
	{
		[textField resignFirstResponder];
	}
	
	return YES;
}

/* This method is called whenever a textField is entered into (i.e., begin entering text into it) */
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
	if (textField == self.userID || textField == self.remoteKey)
	{
		/* Set the animations and specify the amount of time frame will animate */
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.3];
		
		// Make changes to the view's frame inside the animation block. They will be animated instead
		// of taking place immediately.
		CGRect rect = self.view.frame;
		
		// Since moving the view up, not only decrease the origin but increase the height so the view 
		// covers the entire screen behind the keyboard.
		rect.origin.y -= keypad_offset_forNewProfile;
		rect.size.height += keypad_offset_forNewProfile;
		
		self.view.frame = rect;
		
		[UIView commitAnimations];
		
		/* Disable the other textField that is currently not being edited */
		if (textField == self.userID)
		{
			self.remoteKey.enabled = FALSE;
			self.returnButton.hidden = FALSE;
		}
		else
			self.userID.enabled = FALSE;
	}
}

/* This method is called whenever a textField is exited (i.e., finished entering text into it) */
- (void)textFieldDidEndEditing:(UITextField *)textField
{
	if (textField == self.userID || textField == self.remoteKey)
	{
		/* Set the animations and specify the amount of time frame will animate */
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.3];
		
		// Make changes to the view's frame inside the animation block. They will be animated instead
		// of taking place immediately.
		CGRect rect = self.view.frame;
		
		// Since moving down, not only increase the origin but decrease the height.
		rect.origin.y += keypad_offset_forNewProfile;
		rect.size.height -= keypad_offset_forNewProfile;
		
		self.view.frame = rect;
		
		[UIView commitAnimations];
		
		/* Re-enable the other textfield */
		if (textField == self.userID)
		{
			self.remoteKey.enabled = TRUE;
			
			self.returnButton.hidden = TRUE;
		}
		else
			self.userID.enabled = TRUE;
	}
}

@end
